$("#connect").on("click", () => {
	Sounds.click.play();

	// 如果已有连接, 先断开旧连接
	if (socket) {
		socket.disconnect();
		socket = null;
	}

	// 后端地址
	const ip = $("#ipInput").val();
	if (!ip) return;

	const roomId = $("#roomInput").val();
	if (!roomId) return;

	// 玩家名称
	const playerName = $("#nameInput").val();
	if (!playerName) return;

	// 连接到后端
	socket = new io(`http://${ip}`, {
		transports: ["websocket"],
		reconnection: false
	});

	socket.on("connect", () => {
		console.log("连接成功, ID:", socket.id);

		// 连接成功后再发送加入请求
		socket.emit("joinServer", { roomId: roomId, playerName: playerName });
	});

	// 切换场景
	socket.on("showSection", scene => {
		sendShowScene(scene);
	});

	// 房间更新
	socket.on("roomUpdate", () => {
		for (let deptId in GameData) {
			var dept = GameData[deptId];
			var deptElement = $(`#room_${deptId}`);
			var statusElement = deptElement.find(".status");

			if (!dept.isAI && dept.playerId != "") {
				statusElement.text(dept.playerName);
				deptElement.addClass("occupied").removeClass("selected").css("pointer-events", "none");
			} else {
				statusElement.text("空闲");
				deptElement.removeClass("occupied").css("pointer-events", "auto");
			}
		}

		$("#start").prop("disabled", false);
	});

	// 发送游戏消息
	socket.on("message", message => {
		Game.sendMessage(message);
	});

	// 游戏结束事件
	socket.on("endGame", () => {
		Game.sendMessage(" ========== 游戏结束 ========== ");
		// 让所有卡牌无法选择点击
		$(".card").css({ "pointer-events": "none", opacity: "0.6" });
		// 渲染关闭按钮
		Game.closeButtonRender();
	});

	// 发送游戏消息
	socket.on("deptUpdate", dept => {
		DeptData = dept;
		// 渲染部门卡牌
		Game.deptCardRender();
		// 渲染部门行动
		Game.deptPointRender();
		// 渲染部门数据
		Game.deptDataRender();
	});

	// 发送游戏消息
	socket.on("dataUpdate", data => {
		GameData = data;
		// 渲染部门进度
		Game.deptRender();
		// 渲染部门力量
		Game.deptPowerRender();
	});

	// 初始化房间数据
	socket.on("initRoom", () => {
		// 渲染进度
		Room.deptRender();
		sendShowScene("#room");
	});
});

// 点击开始游戏
$("#start").on("click", () => {
	Sounds.click.play();
	if (!socket || !socket.connected) return;
	// 发送包给后端
	send("startGame");
});
